package cn.jx.asc.user.controller;

import cn.jx.asc.common.untils.SecurityUtils;
import cn.jx.asc.common.untils.StringToTimeUtils;
import cn.jx.asc.socket.InstructAndResult;
import cn.jx.asc.user.pojo.*;
import cn.jx.asc.user.service.UserService;
import cn.jx.asc.user.vo.DataShow;
import com.alibaba.fastjson.JSONObject;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 周国伟
 * @desc TODO
 * @date 2018/6/6 10:45
 * @describe 后台页面控制
 */
@Controller("userController")
@RequestMapping("/User")
public class UserController {

    @Autowired
    private UserService userService;
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat DateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    @RequestMapping("/home") //从前台登入页面跳转到后台页面
    public String home(){
        return "home";
    }

    @RequestMapping("/intro") //跳转到个人信息设置页面
    public String intro(HttpSession session, Model model){
        User user = (User) session.getAttribute("USER_SESSION");
        model.addAttribute("user",user);
        return "intro";
    }

    @RequestMapping("/control") //跳转到控制页面
    public String control(){
        return "control";
    }

    @RequestMapping("/areaClassification") //跳转到区域分类页面
    public String areaClassification(HttpServletRequest request , Model model){
        //获取到当前用户的userId
        User user = (User)request.getSession().getAttribute("USER_SESSION");
        Integer userId = user.getUserId();
        //根据userId查询当前用户管理的区域
        List<Region> regionList = null;
        if(userId!=null){
            regionList = userService.selectAllByUserId(userId);
            if(regionList!=null){
                model.addAttribute("regionList" ,regionList);
            }
        }
        return "areaClassification";
    }

    @RequestMapping("/groupClassification") //跳转到组分类页面
    public String groupClassification(HttpServletRequest request ,Model model){
        //获取到当前用户的userId
        User user = (User)request.getSession().getAttribute("USER_SESSION");
        Integer userId = user.getUserId();
        //根据用户id查找该用户管理区域内的所有组
        List<Group> groupList = null;
        if(userId!=null){
           groupList =  userService.selectAllGroupByUserId(userId);
           if(groupList!=null){
               model.addAttribute("groupList" ,groupList);
               model.addAttribute("format" ,format);
           }
        }
        return "groupClassification";
    }

    @RequestMapping("/valveClassification") //跳转到阀门分类页面
    public String valveClassification(HttpServletRequest request ,Model model){
        //获取当前用户id
        User user = (User)request.getSession().getAttribute("USER_SESSION");
        Integer userId = user.getUserId();
        //根据用户id查找该用户管理的所有阀门
        List<Valve> valveList = null;
        if(userId!=null){
            valveList = userService.selectAllValveByUserId(userId);
            if(valveList!=null){
                model.addAttribute("valveList" ,valveList);
            }
        }

        return "valveClassification";
    }

    @RequestMapping("/dataShow")         //跳转到当前数据页面
    public String nowDataShow( Model model,HttpServletRequest request){
        /*String groupId = request.getParameter("groupId");*/
        String groupId = "300000069";
        List<Region> regionList = userService.findRegionWithGroup();
        model.addAttribute("regionList",regionList);
        List<Valve> valveList = userService.findValveByGroupId(Integer.valueOf(groupId));
        model.addAttribute("valveList",valveList);
        System.out.println("valveList---" + valveList);

        return "nowDataShow";
    }
    @RequestMapping("/historyDataShow") //跳转到历史查询数据页面
    public String dataShow(DataShow dataShow,Model model){
            return "historyDataShow";
    }

    @RequestMapping("/specialist") //跳转到专家方案显示页面
    public String specialist(){

        return "specialist";
    }

    @RequestMapping("/FindVaListByGroupId")  //根据组id找阀门集合
    public String findValveListByGroupId(HttpServletRequest request,Model model){

        String groupId = request.getParameter("groupId");
        List<Valve> valveList = userService.findValveData(groupId);
        model.addAttribute("valveList",valveList);
        return "nowDataShow";
    }

    @RequestMapping("/valveController") //跳转到阀门控制页面
    public String valveController(Model model,HttpServletRequest request){

        List<Group> groupList = userService.findGroupAndValve();
        model.addAttribute("groupList",groupList);
        List<Region> regionList = userService.findRegionWithGroup();
        model.addAttribute("regionList",regionList);
        String groupId = request.getParameter("groupId");
        if(groupId!=null){
            List<Valve> valveList = userService.findValveData(groupId);
            model.addAttribute("valveList",valveList);
        }
        return "valveController";
    }
    @RequestMapping("/timing")     //阀门控制中的定时模式
    @ResponseBody
    public String timing(@RequestBody String result) throws JSONException {

        JSONObject object = JSONObject.parseObject(result);
        List<Group> groupList = userService.findGroupAndValve();
        String controlType = (String) object.get("controlType");
        String valveId = (String) object.get("valveId");
        List<String>  ListStartTime = (List<String>) object.get("ListStartTime");
        List<String> ListStopTime = (List<String>) object.get("ListStopTime");
        List<String> listIntervalDay = (List<String>) object.get("listIntervalDay");
        //将开始时间,结束时间,间隔时间拼接成字符串
        String times1 =  ListStartTime.get(0) + ListStopTime.get(0) + listIntervalDay.get(0);  //时段1
        String times2 = ListStartTime.get(1) + ListStopTime.get(1) + listIntervalDay.get(1);   //时段2
        String times3 = ListStartTime.get(2) + ListStopTime.get(2) + listIntervalDay.get(2);   //时段3
        //将字符串转换成终端需要的格式
        String timesStr1 = StringToTimeUtils.timeToString(times1);
        String timesStr2 = StringToTimeUtils.timeToString(times2);
        String timesStr3 = StringToTimeUtils.timeToString(times3);
        //将阀门id转换成valveNum
        String valveNum = "";
        if(valveId.equals("400000066")){
            valveNum = "1";
        }else if(valveId.equals("400000067")){
            valveNum = "2";
        }else if(valveId.equals("400000068")){
            valveNum = "3";
        }else if(valveId.equals("400000069")){
            valveNum = "4";
        }
        //发送给终端的指令
        String timeData = "{'flags':'3','valveNum':"+valveNum+",'time1':'"+timesStr1+"','time2':'"+timesStr2+"','time3':'"+timesStr3+"'}";
        //将数据转换为json对象
        org.json.JSONObject jsonTimeData = new org.json.JSONObject(timeData);
        //发送指令
        int timeId = InstructAndResult.sendInstructs(123456 ,jsonTimeData);
        //返回结果
        org.json.JSONObject resultTimeJson = InstructAndResult.getResult(timeId);
        System.out.println("定时返回结果***" + resultTimeJson);
        /*int rows = userService.updateValve(valveId,controlType,groupList); //跟新阀门控制方式
        int rows1 = userService.addControl(ListStartTime,ListStopTime,listIntervalDay,valveId,groupList);  //用户自己设计的浇灌方案
        if(rows>0&&rows1>0){
            return "OK";
        }else {
            return "fail";
        }*/
        Integer timeFlag = resultTimeJson.getInt("flags");
        if (timeFlag != -1 && timeFlag != 0) {
            return "OK";
        } else {
            return "fail";
        }

    }
    @RequestMapping("/ration")   //阀门控制中的定量模式
    @ResponseBody
    public String ration(HttpServletRequest request){
        List<Region> regionList = userService.findRegionWithGroup();
        //接收浏览器数据
        String humidity = request.getParameter("humidity");
        String groupId = request.getParameter("groupId");
        String controlType = request.getParameter("controlType");
        //发送给终端的指令
        String humData = "{'flags':'4','hum':"+humidity+"}";       //湿度
        String conData = "{'flags':'5','valveNum:':'5','data':'3'}";    //控制
        org.json.JSONObject jsonHumData = null;
        org.json.JSONObject jsonConData = null;
        try {
            jsonHumData = new org.json.JSONObject(humData);
            jsonConData = new org.json.JSONObject(conData);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //向终端发送请求数据
        int humId = InstructAndResult.sendInstructs(123456, jsonHumData);
        int conId = InstructAndResult.sendInstructs(123456, jsonConData);
        //获得终端返回的结果
        /*org.json.JSONObject resultHumJson = InstructAndResult.getResult(humId);
        org.json.JSONObject resultConJson = InstructAndResult.getResult(conId);
        取出结果中的flag

            Integer humFlag = resultHumJson.getInt("flag");
            Integer conFlag = resultConJson.getInt("flag");
            if (humFlag != -1 && humFlag != 0 && conFlag != -1 && conFlag != 0) {
                return "OK";
            } else {
                return "fail";
            }
           int rows = userService.addHumidity(humidity,groupId,regionList);
                int rows1 = userService.updateValve_ration(groupId,controlType,regionList);//更新阀门控制方式
                if(rows>0&&rows1>0){
                    return "OK";
                }else {
                    return "fail";
                }
            }else{
                return "fail";
            }
        } catch (JSONException e) {
            System.out.println("****取出结果失败****");
            e.printStackTrace();
    }
        return "fail";*/
        return "OK";
    }

    @RequestMapping("/userinfo")      //用户查询当前的用户
    @ResponseBody
    public User getUser(HttpSession session){
        User user = (User) session.getAttribute("USER_SESSION");
        return user;
    }
    @RequestMapping("/update")  //更新修改用户信息
    @ResponseBody
    public String update(User user, HttpSession session, HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {

        String userName = request.getParameter("userName");
        String realName =request.getParameter("realName");
        String password =request.getParameter("password");
        String repassword =request.getParameter("repassword");
        String mail =request.getParameter("mail");
        String tel =request.getParameter("tel");
        String address =request.getParameter("address");

        User user1 = (User) session.getAttribute("USER_SESSION");
        user.setUserId(user1.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(password));
        Pattern p =  Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");//邮箱的正则表达式
        Matcher m = p.matcher(mail);

        Pattern pattern = Pattern.compile("[0-9]*"); //判断字符串是否是数字,验证电话号码是否正确
        Matcher isNum = pattern.matcher(tel);

       if(userName==""||realName==""||password==""||repassword==""){
           return "fail";
       }else if(!m.matches()||!isNum.matches()||!password.equals(repassword)){
           return "fail";
       }else  if(userService.updateUser(user)>0){
           return "OK";
       }else {
           return "fail";
       }

    }

    @RequestMapping("/updataValvaByid") //阀门控制中的手动控制
    @ResponseBody
    public String updataValvaByid(@RequestBody String result) throws JSONException {
        JSONObject object = JSONObject.parseObject(result);
        String controlType = (String) object.get("controlType");
        List<String> valvaIdList = (List<String>) object.get("valvaIdList");
        List<String> buttonvalList = (List<String>) object.get("button_valList");
        System.out.println("buttonvalList------"+buttonvalList);
        //四个阀门的状态
        String valve1 = buttonvalList.get(0).equals("打开")?"1":"0";
        String valve2 = buttonvalList.get(1).equals("打开")?"1":"0";
        String valve3 = buttonvalList.get(2).equals("打开")?"1":"0";
        String valve4 = buttonvalList.get(3).equals("打开")?"1":"0";
        //发送给终端的指令
        String valveData = "";  //阀门状态
        String conData = "";    //控制方式
        //如果四个阀门状态均相等,valveNum则为5
        if(valve1.equals("1")&&valve2.equals("1")&&valve3.equals("1")&&valve4.equals("1")){
            valveData = "{'flags':'2','data':{'valveNum':'5','state':'1'}";
            conData = "{'flags':'5','valveNum':'5','data':'1'}";
            //将数据转换为json对象
            org.json.JSONObject jsonValveData = new org.json.JSONObject(valveData);
            org.json.JSONObject jsonConData = new org.json.JSONObject(conData);
            //发送指令
            int ValveId = InstructAndResult.sendInstructs(123456 ,jsonValveData);
            int ConId = InstructAndResult.sendInstructs(123456 ,jsonConData);
            return "OK";
        }else if(valve1.equals("0")&&valve2.equals("0")&&valve3.equals("0")&&valve4.equals("0")){
            valveData = "{'flags':'2','data':{'valveNum':'5','state':'0'}";
            conData = "{'flags':'5','valveNum':'5','data':'1'}";
            //将数据转换为json对象
            org.json.JSONObject jsonValveData = new org.json.JSONObject(valveData);
            org.json.JSONObject jsonConData = new org.json.JSONObject(conData);
            //发送指令
            int ValveId = InstructAndResult.sendInstructs(123456 ,jsonValveData);
            int ConId = InstructAndResult.sendInstructs(123456 ,jsonConData);
            return "OK";
        }
        //发送给终端的指令
        String valveData1 = "{'flags':'2','data':{'valveNum':'1','state':'"+valve1+"'}";
        String valveData2 = "{'flags':'2','data':{'valveNum':'1','state':'"+valve2+"'}";
        String valveData3 = "{'flags':'2','data':{'valveNum':'1','state':'"+valve3+"'}";
        String valveData4 = "{'flags':'2','data':{'valveNum':'1','state':'"+valve4+"'}";
        conData = "{'flags':'5','valveNum':'5','data':'1'}";
        //将数据转换为json对象
        org.json.JSONObject jsonValveData1 = new org.json.JSONObject(valveData1);
        org.json.JSONObject jsonValveData2 = new org.json.JSONObject(valveData2);
        org.json.JSONObject jsonValveData3 = new org.json.JSONObject(valveData3);
        org.json.JSONObject jsonValveData4 = new org.json.JSONObject(valveData4);
        org.json.JSONObject jsonConData = new org.json.JSONObject(conData);
        //发送指令
        int ValveId1 = InstructAndResult.sendInstructs(123456 ,jsonValveData1);
        int ValveId2 = InstructAndResult.sendInstructs(123456 ,jsonValveData2);
        int ValveId3 = InstructAndResult.sendInstructs(123456 ,jsonValveData3);
        int ValveId4 = InstructAndResult.sendInstructs(123456 ,jsonValveData4);
        int ConId = InstructAndResult.sendInstructs(123456 ,jsonConData);
        return "OK";
        /*int rows = userService.updateValveByVaList(valvaIdList,controlType,buttonvalList);
        if(rows>0){
            return "OK";
        }else {
            return "fail";
        }*/
    }


}
